<template>
  <div class="el-scroll-box">
    <el-scrollbar>
      <div class="video-wrapper">
        <div class="video-left" :style="{width:isOpenMeun?'calc(100% - 320px)':'100%' }">
          <div class="top-title">
            <button class="back-btn" @click="$router.go(-1)">返回课程</button>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item>{{ currentVideoInfo.pName }}</el-breadcrumb-item>
              <el-breadcrumb-item>{{ currentVideoInfo.name }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div id="mui-player" />
          <button class="back-btn" @click="nextPlay">下一课时</button>
        </div>
        <div class="video-right" :style="{right:isOpenMeun?'0':'-320px' }">
          <div class="open-close" @click="isOpenMeun=!isOpenMeun">
            <i :class="isOpenMeun?'el-icon-s-unfold':'el-icon-s-fold'" />
          </div>

          <el-scrollbar>
            <el-collapse v-model="activeNames">
              <el-collapse-item v-for="item in bookList" :key="item.id" :name="item.listid">
                <template slot="title">
                  <span class="col-title">
                    <i class="header-icon el-icon-s-grid" />{{ item.name }}
                  </span>
                </template>
                <ul class="video-ul">
                  <li v-for="it in item.nodes" :key="it.detailid" :class="[it.play?'play':'']" @click="changeCurrentVideoUrl(it)">
                    <div class="li-left">
                      <div class="study-circle">
                        <div class="inner-white" />
                      </div>
                      <span>{{ it.name }}</span>
                    </div>
                  </li>
                </ul>
              </el-collapse-item>
            </el-collapse>
          </el-scrollbar>

        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
// api
import { getLearnBook, saveLearnBook } from '@/api/learnCenter'
// utils
import { fileHostUrl } from '@/utils'
// video
import 'mui-player/dist/mui-player.min.css'
import MuiPlayer from 'mui-player'
import MuiPlayerDesktopPlugin from 'mui-player-desktop-plugin'
// import Hls from 'hls.js'
// import Flv from 'flv.js'
export default {
  name: 'PlayVideo',
  data() {
    return {
      bookList: [], // 课程列表
      isOpenMeun: true, // 侧边栏是否展开
      activeNames: [], // 侧边栏展开项目
      mp: null, // 播放器实例
      oldCurrentVideoInfo: {},
      currentVideoInfo: { // 当前播放视频信息
        id: '',
        pid: '',
        url: '',
        name: '',
        pName: '',
        startTime: '',
        totalTime: ''
      },
      routeParams: {} // 路由参数
    }
  },
  beforeRouteLeave(to, from, next) {
    // 存储用来获取暂停播放视频上传进度使用
    this.oldCurrentVideoInfo = JSON.parse(JSON.stringify(this.currentVideoInfo))
    next()
  },
  created() {
    if (this.$route.params.detailid) {
      this.routeParams = this.$route.params
    } else {
      const routeParams = window.sessionStorage.getItem('route_params_' + this.$route.params.id)
      this.routeParams = JSON.parse(routeParams).data
    }
  },
  mounted() {
    this.getCourseInfo()
  },
  destroyed() {
    this.mp && this.mp.destory() // 销毁实例
  },
  methods: {
    // 获取课程列表
    getCourseInfo() {
      const vPar = new this.ParamArr()
      vPar.setStr('ID', this.routeParams.bookid) // 课程id
      getLearnBook(vPar).then(vPar => {
        // 视频列表
        const bookList = []
        // 获取章节
        this.getBookList(vPar, bookList)
      })
    },
    // 获取章节列表
    getBookList(vPar, bookList) {
      const nodes = []
      const table = new this.SQLTable(vPar.getTable('k_learn_book_list'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['listid'] = table.getValueByName('ListID')
        node['bookid'] = table.getValueByName('BookID')
        node['text'] = table.getValueByName('Name')
        node['name'] = table.getValueByName('Name')
        node['remark'] = table.getValueByName('Remark')
        nodes.push(node)
        table.next()
      }
      bookList = [...bookList, ...nodes]
      // 获取章节视频
      this.getVideoList(vPar, bookList)
    },
    // 获取章节视频
    getVideoList(vPar, bookList) {
      const nodes = []
      const table = new this.SQLTable(vPar.getTable('k_learn_book_detail'))
      // console.log(1, table)
      table.first()
      while (!table.eof()) {
        const node = {}
        node['detailid'] = table.getValueByName('DetailID')
        node['listid'] = table.getValueByName('ListID')
        node['bookid'] = table.getValueByName('BookID')
        node['name'] = table.getValueByName('Name')
        node['filePath'] = table.getValueByName('FilePath')
        node['fileName'] = table.getValueByName('FileName')
        node['fileTime'] = table.getValueByName('FileTime')
        if (node['detailid'] === this.routeParams.detailid) {
          node['play'] = true // 当前课程标志
          this.activeNames = [node['listid']]
          this.currentVideoInfo.detailid = node['detailid']
          this.currentVideoInfo.listid = node['listid']
          this.currentVideoInfo.bookid = node['bookid']
          this.currentVideoInfo.fileTime = node['fileTime']
          this.currentVideoInfo.url = fileHostUrl + '/' + node['filePath']
          this.currentVideoInfo.name = node['name']
          bookList.forEach(item => {
            if (item.listid === node['listid']) {
              this.currentVideoInfo.listName = item['name']
            }
          })
        }
        nodes.push(node)
        table.next()
      }

      const detaildList = nodes // 章节视频

      // 获取当前视频播放时长
      this.getVideoListPlayTime(vPar, detaildList, bookList)
    },
    // 获取当前视频播放时长
    getVideoListPlayTime(vPar, detaildList, bookList) {
      const detaildTimeList = []
      const table = new this.SQLTable(vPar.getTable('k_learn_book_user_detail'))
      table.first()
      while (!table.eof()) {
        const node = {}
        node['detailid'] = table.getValueByName('DetailID')
        node['listid'] = table.getValueByName('ListID')
        node['posTime'] = table.getValueByName('PosTime')
        node['createTime'] = table.getValueByName('CreateTime')
        detaildTimeList.push(node)
        table.next()
      }
      // 视频匹配时长
      detaildList.forEach(it1 => {
        detaildTimeList.forEach(it2 => {
          if (it1.detailid === it2.detailid) {
            it1.posTime = it2.posTime
          }
          // 当前视频播放进度
          if (it2['detailid'] === this.routeParams.detailid) {
            this.currentVideoInfo.posTime = it2.posTime
          }
        })
      })
      // 章节匹配视频
      bookList.forEach(it1 => {
        detaildList.forEach(it2 => {
          if (it1.listid === it2.listid) {
            if (it1.nodes) {
              it1.nodes.push(it2)
            } else {
              it1.nodes = [it2]
            }
          }
        })
      })
      // 存储用来获取暂停播放视频上传进度使用
      this.oldCurrentVideoInfo = JSON.parse(JSON.stringify(this.currentVideoInfo))

      this.bookList = bookList
      // console.log(this.bookList)
      // 初始化播放器
      this.initVideo()
    },
    // 初始化播放器
    initVideo() {
      this.mp = new MuiPlayer({
        container: '#mui-player',
        // title: this.currentVideoInfo.name,
        src: this.currentVideoInfo.url,
        height: '100%',
        width: '100%',
        lang: 'zh-cn',
        autoplay: true, // 进入页面自动播放
        plugins: [
          new MuiPlayerDesktopPlugin({
            contextmenu: {}, // 右键菜单组配置
            leaveHiddenControls: true // 鼠标指针移出播放器时是否隐藏控件
          })
        ]
      })
      this.mp.on('ready', (event) => {
        const video = this.mp.video()
        video.addEventListener('ended', () => {
          // 播放结束之后自动播放下一个课时
          this.nextPlay()
        }, false)
        video.addEventListener('pause', () => {
          // 当前播放视频学习进度
          const vPar = new this.ParamArr()
          vPar.setStr('DetailID', this.oldCurrentVideoInfo.detailid)
          vPar.setStr('ListID', this.oldCurrentVideoInfo.listid)
          vPar.setStr('BookID', this.oldCurrentVideoInfo.bookid)
          vPar.setInt('PosTime', Math.floor(video.currentTime))
          // console.log('saveLearnBook')
          // console.log(vPar)
          if (!this.oldCurrentVideoInfo.listid) return this.$message.error('没有章节id')
          if (!this.oldCurrentVideoInfo.bookid) return this.$message.error('没有课程id')
          saveLearnBook(vPar).then(vPar => {})
        }, false)

        // 获取此视频的学习进度， 设置播放时间
        if (this.currentVideoInfo.posTime) {
          const posTime = parseInt(this.currentVideoInfo.posTime)
          const fileTime = parseInt(this.currentVideoInfo.fileTime)
          const precent = Math.floor((posTime / fileTime) * 100)
          if (parseInt(precent) <= 95) { // 播放进度大于95就从0开始播放
            video.currentTime = parseInt(this.currentVideoInfo.posTime)
          }
        }
      })
    },
    // 侧边栏点击播放
    changeCurrentVideoUrl(item) {
      // 存储用来获取暂停播放视频上传进度使用
      this.oldCurrentVideoInfo = JSON.parse(JSON.stringify(this.currentVideoInfo))
      this.bookList.forEach(it1 => {
        if (it1.nodes) {
          it1.nodes.forEach(it2 => {
            if (it2.detailid === item.detailid) {
              this.$set(it2, 'play', true)
              this.currentVideoInfo.detailid = it2.detailid
              this.currentVideoInfo.listid = it2.listid
              this.currentVideoInfo.bookid = it2.bookid
              this.currentVideoInfo.posTime = it2.posTime
              this.currentVideoInfo.fileTime = it2.fileTime
              this.currentVideoInfo.url = fileHostUrl + '/' + it2['filePath']
              this.currentVideoInfo.name = it2.name
              this.currentVideoInfo.listName = it1.name
              // 修改播放地址
              this.mp.reloadUrl(this.currentVideoInfo.url)
              // 展开右侧tab
              this.activeNames = [...this.activeNames, it1.listid]
              // 修改地址栏当前播放视频id
              this.$router.replace({ name: 'PlayVideo', params: { id: this.currentVideoInfo.detailid }})
            } else {
              this.$set(it2, 'play', false)
            }
          })
        }
      })
    },
    // 下一课时
    nextPlay() {
      const video = []
      let index = -1
      this.bookList.forEach(it1 => {
        if (it1.nodes) {
          const nodes = it1.nodes
          nodes.forEach((it2, i) => {
            video.push(it2)
          })
        }
      })
      video.forEach((item, i) => {
        if (item.detailid === this.currentVideoInfo.detailid) {
          index = i
        }
      })
      if (index !== -1) {
        if (index === (video.length - 1)) {
          index = 0
        } else {
          index = index + 1
        }
        this.changeCurrentVideoUrl(video[index])
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
  .el-scrollbar__view {
    height: 100%;
  }
}
.el-scroll-box {
  width: 100%;
  height: 100%;
  .el-scrollbar {
    height:100%
  }
}
.video-wrapper {
  padding: 10px;
  width: 100%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  .video-left {
    transition: all .5s ease-in;
    display: flex;
    flex-direction: column;
    .top-title {
      display: flex;
      align-items: center;
    }
    #mui-player {
      flex: 1;
      margin:5px 0;
    }
    .back-btn {
      background: $primaryColor;
      margin-right: 10px;
      width: 120px;
      height: 30px;
      border: none;
      font-size: 13px;
      color: #fff;
      cursor: pointer;
    }
  }
  .video-right {
    transition: all .5s ease-in;
    position: absolute;
    height: 100%;
    top: 0;
    box-shadow: 0px 1px 8px #333;
    width: 320px;
    background: #abadb0;
    .open-close {
      box-sizing: border-box;
      padding: 5px;
      border-radius: 4px;
      position: absolute;
      top: 10px;
      left: -25px;
      cursor: pointer;
      font-size: 18px;
      background: $primaryColor;
      i {
        color: #fff;
      }
    }
  }
}

.col-title {
  margin-left: 10px;
  color: $primaryColor;
  font-size: 15px;
  i {
    margin-right: 10px;
  }
}
.video-ul {
  padding-left: 5px;
  li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 5px;
    cursor: pointer;
    padding: 10px;
    &.play {
      background-color: $infoColor;
    }
    &:hover {
      background-color: $infoColor;
    }
    .li-left {
      display: flex;
      align-items: center;
      justify-content: center;
      .study-circle {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        border: 2px solid $primaryColor;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        .inner-white {
          width: 7px;
          height: 7px;
          background-color: #fff;
          border-radius: 50%;
        }
      }
    }
    .li-right {
      span {
        margin-right: 10px;
      }
    }

  }
}
::v-deep .el-collapse-item__content {
  padding-bottom: 0;
}
</style>
